﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using GIFT_SHOP_MVC.Models;
using System.Security.Cryptography;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace GIFT_SHOP_MVC.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        Models.GiftShop_LinQDataContext data = new Models.GiftShop_LinQDataContext();

        public string Encrypt(string password)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(password);

            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(password));

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(string userid,string pass,bool remember)
        {
            pass = Encrypt(pass);
            var user = data.Users.Where(u => u.UserName == userid && u.Pass == pass).ToList();

            if (user.Any())
            {
                Session["login"] = true;
                Session["user"] = user[0];
                if (user[0].Admin == true)
                    return RedirectToAction("Index", "Admin");
            }
            else
                Session["login"] = false;

            return Redirect(Request.UrlReferrer.ToString()); 
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            Session["login"]= Session["Cart"] = Session["user"] = Session["url"] = Session["table"] = Session["available"] = Session["type"] = null;
            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public void CreateCaptcha()
        {
            string captcha = Encrypt(DateTime.Now.ToString()).Substring(22, 5);
            string[] fonts = { "Arial Black", "VNI-Ariston","VNI-Chaucer", "VNI-Duff", "VNI=Harrington" };
            using (Bitmap bmp = new Bitmap(120, 30))
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    HatchBrush brush = new HatchBrush(HatchStyle.Wave, Color.White, Color.Wheat);
                    g.FillRegion(brush, g.Clip);
                    Random rand = new Random();
                    for (int i = 0; i < 5; i++)
                    {
                        Font font = new Font(fonts[rand.Next(fonts.Length)], 12, FontStyle.Bold | FontStyle.Italic);
                        SizeF size = g.MeasureString(captcha[i].ToString(), font);
                        g.DrawString(captcha[i].ToString(), font, Brushes.Coral, i * 20 + 3, rand.Next(2, 10));
                        font.Dispose();
                    }
                    var path = Path.Combine(Server.MapPath("~/Content/images"),"captcha.jpg");
                    bmp.Save(path, ImageFormat.Jpeg);
                }
            }
            Session["captcha"] = captcha;
        }

        public ActionResult Register()
        {
            Session["available"] = true;
            CreateCaptcha();
            var a = Session["captcha"];
            return View();
        }

        [HttpPost]       
        public ActionResult Register(RegisterModel newUser)
        {
            Session["available"] = true;
            Session["correct"] = true;
            if (!ModelState.IsValid)
                return View();
            else
            {
                if (newUser.Captcha != (string)Session["captcha"])
                {
                    Session["correct"] = false;
                    return View();
                }

                var user = data.Users.Where(u => u.UserName == newUser.UserName).ToList();
                if (user.Any())
                {
                    Session["available"] = false;
                    return View();
                }
                else
                {
                    Models.User nUser = new Models.User();
                    nUser.UserName = newUser.UserName;
                    nUser.Pass = Encrypt(newUser.Password);
                    nUser.HoTen = newUser.Name;
                    nUser.DiaChi = newUser.Address;
                    nUser.DienThoai = newUser.Phone;
                    nUser.Admin = false;
                    nUser.Ma_TT = 1;
                    data.Users.InsertOnSubmit(nUser);
                    data.SubmitChanges();

                    Session["login"] = true;
                    Session["user"] = nUser;
                    return RedirectToAction("Index", "Home");
                }
            }
            
        }

        public ActionResult Profile()
        {
            Models.User user = (Models.User)Session["user"];
            return View(user);
        }

        [HttpPost]
        public ActionResult Profile(Models.User user)
        {
            if (!ModelState.IsValid)
                return View();

            Session["checkuser"] = true;
            var us = data.Users.Where(u => (u.UserName == user.UserName && u.MaUser != user.MaUser)).ToList();
            if (us.Any())
            {
                Session["checkuser"] = false;
                return View();
            }
            var avaius = data.Users.Single(u => u.MaUser == user.MaUser);
            avaius.HoTen = user.HoTen;
            avaius.UserName = user.UserName;
            avaius.DiaChi = user.DiaChi;
            avaius.DienThoai = user.DienThoai;
            data.SubmitChanges();
            Session["user"] = avaius;
            return RedirectToAction("Index","Home");
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        //[Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        public bool ChangePass(Models.User us, string oldPass, string newPass)
        {
            if (Encrypt(oldPass) == us.Pass)
            {
                Models.User user = data.Users.Single(u => u.MaUser == us.MaUser);
                user.Pass = Encrypt(newPass);
                data.SubmitChanges();
                Session["user"] = user;
                return true;
            }
            return false;
        }

        //[Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                Models.User us = (Models.User)Session["user"];
                if (ChangePass(us,model.OldPassword,model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

    }
}
